package com.topnav.mc.admin.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.topnav.mc.admin.entity.*;
import com.topnav.mc.admin.entity.bean.RoleBean;
import com.topnav.mc.admin.entity.param.RoleParam;
import com.topnav.mc.admin.service.*;
import com.topnav.mc.base.mc.McServiceImpl;
import com.topnav.mc.document.entity.Document;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.uitls.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.js.lib.exception.CustomException;
import com.topnav.mc.admin.dao.mapper.RoleMapper;
import com.topnav.mc.base.CommServiceImpl;
@Service
@Slf4j
public class RoleServiceImpl extends McServiceImpl<RoleMapper,Role, RoleBean, RoleParam> implements IRoleService{
	@Autowired
	private IRolePermissionService rolePermissionService;
	@Autowired
	private IUserOrganizaitonService userOrganizaitonService;
	@Autowired
	private IUserRoleService userRoleService;
	@Autowired
	private IRoleAuthorizationService roleAuthorizationService;


	@Override
	public boolean beforeDelete(Role entity){
		LambdaQueryWrapper<RolePermission> rolePermissionWrapper = new LambdaQueryWrapper<>();
		rolePermissionWrapper.eq(RolePermission::getRoleId,entity.getId());
		if (rolePermissionService.getOne(rolePermissionWrapper,false) != null){
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_DELETE_ROLE_USED_BY_PERMISSION);
		}

		LambdaQueryWrapper<UserOrganizaiton> userOrganizaitonWrapper = new LambdaQueryWrapper<>();
		userOrganizaitonWrapper.eq(UserOrganizaiton::getRoleId,entity.getId());
		if (userOrganizaitonService.getOne(userOrganizaitonWrapper,false) != null){
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_DELETE_ROLE_USED_BY_ORGANIZATION);
			//throw new CustomException(-1,"此角色已分配用户部门权限，请先解除用户部门权限，再删除");
		}

		LambdaQueryWrapper<UserRole> userRoleWrapper = new LambdaQueryWrapper<>();
		userRoleWrapper.eq(UserRole::getRoleId,entity.getId());
		if (userRoleService.getOne(userRoleWrapper,false) != null){
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_DELETE_ROLE_USED_BY_USER);
		}

		LambdaQueryWrapper<RoleAuthorization> raWrapper = new LambdaQueryWrapper<RoleAuthorization>().eq(RoleAuthorization::getRoleId,entity.getId());
		if (roleAuthorizationService.getOne(raWrapper,false) != null){
			//此角色已有分配权限，请解除分配的权限，再删除
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_DELETE_AUTORIZATION_USED_BY_ROLE);
		}
		return true;
	}

	@Override
	public boolean beforeUpdate(Role entity){return true;}



	@Override
	public Role getOneHighLeveByUserOrgRole(Long userId, Long orgId) {
		return this.getBaseMapper().getOneHighLeveByUserOrgRole(userId,orgId);
	}

	@Override
	public Role getOneHighLevelByUserRole(Long userId) {
		return this.getBaseMapper().getOneHighLevelByUserRole(userId);
	}

	/**
	 * 查询列表
	 *
	 * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
	 */
	@Override
	public List<Role> list(Wrapper<Role> queryWrapper) {
		return super.list(queryWrapper);
		/*
		QueryWrapper<Role> wrapper = new QueryWrapper<Role>();
		if (queryWrapper.getEntity() != null){
			if (queryWrapper.getEntity().getId()!=null){
				wrapper.eq("id", queryWrapper.getEntity().getId());
			}
			if (queryWrapper.getEntity().getRoleLevel()!=null){
				wrapper.eq("role_level", queryWrapper.getEntity().getRoleLevel());
			}

			if (!StringUtils.isEmpty(queryWrapper.getEntity().getCode())){
				wrapper.eq("code", queryWrapper.getEntity().getCode());
			}
			if (!StringUtils.isEmpty(queryWrapper.getEntity().getName())){
				wrapper.eq("name", queryWrapper.getEntity().getName());
			}
		}
		return getBaseMapper().selectList(wrapper);*/
	}
	@Override
	@Transactional
	public boolean remove(Wrapper<Role> queryWrapper) {
		return super.remove(queryWrapper);

		//先删除权限
/*		QueryWrapper<RolePermission> wrapper1 = new QueryWrapper<RolePermission>()
				.eq("role_id", queryWrapper.getEntity().getId());
		rolePermissionService.remove(wrapper1);
		//再删除本实体
		SqlHelper.retBool(this.getBaseMapper().delete(queryWrapper));

		return true;*/
	}
	@Override
	@Transactional
	public boolean save(Role entity) {
		if (this.getOne(new QueryWrapper<Role>().eq("code",entity.getCode()), true) != null){
			//throw new CustomException(-1,"角色  %s 已存在",entity.getCode());
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_PARAM_ROLE_EXISTS);
		}
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		Boolean result = SqlHelper.retBool(getBaseMapper().insert(entity));
		log.info(entity.getId().toString());
		if (result){
			if (!CollectionUtils.isEmpty(entity.getPermissions())){
				List<RolePermission> batch = new ArrayList<>();
				for(Permission p: entity.getPermissions()){
					RolePermission rp = new RolePermission();
					rp.setRoleId(entity.getId());
					rp.setPermissionId(p.getId());
					rp.setCreateTime(new Date());
					rp.setUpdateTime(new Date());
					batch.add(rp);
				}
				result = rolePermissionService.saveBatch(batch);
			}
		}
		return result;
	}

	@Override
	@Transactional
	public boolean updateById(Role entity) {
		QueryWrapper<Role> wrapper = new QueryWrapper<Role>()
				.eq("code", entity.getCode()).ne("id", entity.getId());
		if (this.getOne(wrapper, true) != null){
			//throw new CustomException(-1,"角色  %s 已存在",entity.getCode());
			throw ExceptionUtil.commonException(ExceptionMsg.ERROR_PARAM_ROLE_EXISTS);
		}
		entity.setUpdateTime(new Date());
		boolean result = SqlHelper.retBool(this.getBaseMapper().updateById(entity));
		/** 先删除 权限*/
		if (result){
			QueryWrapper<RolePermission> wrapper1 = new QueryWrapper<RolePermission>()
					.eq("role_id", entity.getId());
			rolePermissionService.remove(wrapper1);
			/** 再加 */
			if (!CollectionUtils.isEmpty(entity.getPermissions())){
				List<RolePermission> batch = new ArrayList<>();
				for(Permission p: entity.getPermissions()){
					RolePermission rp = new RolePermission();
					rp.setRoleId(entity.getId());
					rp.setPermissionId(p.getId());
					rp.setCreateTime(new Date());
					rp.setUpdateTime(new Date());
					batch.add(rp);
				}
				result = rolePermissionService.saveBatch(batch);
			}
		}
		return result;
	}










}
